const express = require('express');
const expressWs = require('express-ws');
const pty = require('node-pty');
const os = require('os');
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash'; // powershell.exe cmd.exe
const app = express();
expressWs(app);

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    next();
});

app.ws('/socket', (ws) => {
    const ptyProcess = pty.spawn(shell, [], {
        name: 'xptyProcess-color',
        cols: 80,
        rows: 30,
        cwd: process.env.HOME,
        env: process.env,
    });
    ptyProcess.onData((data) => {
        console.log('------ptyProcess:', data);
        ws.send(data);
    });
    ws.on('message', (data) => {
        console.log('-------ws:', data);
        if (data === 'ping') {
            return;
        }
        try {
            const {
                resize: [cols, rows],
            } = JSON.parse(data);
            ptyProcess.resize(cols, rows);
            // ptyProcess.write('ls\r');
            return;
        } catch (error) {
            ptyProcess.write(data);
        }
    });
});

app.listen(8001, () => {
    console.log(`成功监听端口：8001`);
});
